package com.xjj.tree;

import com.xjj.TreeNode;

import java.util.HashMap;
import java.util.Map;

public class M0106ConstructBinaryTreeFromInorderAndPostorderTraversal {

    int[] inorder;

    int[] postorder;

    Map<Integer, Integer> map = new HashMap<>();

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        this.inorder = inorder;
        this.postorder = postorder;
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return find(0, inorder.length - 1, 0, postorder.length - 1);
    }

    private TreeNode find(int inLeft, int inRight, int postLeft, int postRight) {
        if (inLeft > inRight) {
            return null;
        }
        // 后序最后一个为root
        TreeNode root = new TreeNode(postorder[postRight]);
        int index = map.get(postorder[postRight]);
        //1 0 2
        //1 2 0
        root.left = find(inLeft, index - 1, postLeft, postLeft + (index - inLeft) - 1);
        root.right = find(index + 1, inRight, postLeft + (index - inLeft), postRight - 1);
        return root;
    }

}
